package com.danan.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.danan.realtime.app.BaseApp;
import com.danan.realtime.common.Constant;
import com.danan.realtime.pojo.CartAddUuBean;
import com.danan.realtime.util.SinkUtil;
import com.danan.realtime.util.TimeUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author NanHuang
 * @Date 2023/1/26
 */
public class DwsApp_6_trade_cart_add_uu_window extends BaseApp {
    public static void main(String[] args) {
        new DwsApp_6_trade_cart_add_uu_window().init(
                5006,
                3,
                "DwsApp_6_trade_cart_add_uu_window",
                Constant.TOPIC_DWD_TRADE_CART_ADD
        );
    }
    @Override
    public void invoke(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        // 1 过滤数据，封装为POJO
        SingleOutputStreamOperator<CartAddUuBean> beanDs = toCartAddUuBean(ds);
        // 2 开窗聚合
        SingleOutputStreamOperator<CartAddUuBean> resultDs = windowAndAgg(beanDs);
        // 3 将结果写入Clickhouse中
        resultDs.addSink(SinkUtil.getClickhouseSink(Constant.TOPIC_DWS_TRADE_CART_ADD_UU_WINDOW,CartAddUuBean.class));
    }

    private SingleOutputStreamOperator<CartAddUuBean> windowAndAgg(SingleOutputStreamOperator<CartAddUuBean> ds) {
        // 1 创建水印策略
        WatermarkStrategy<CartAddUuBean> strategy = WatermarkStrategy.<CartAddUuBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((s, l) -> s.getTs())
                .withIdleness(Duration.ofSeconds(60));
        // 2 开窗聚合
        return ds.assignTimestampsAndWatermarks(strategy)
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<CartAddUuBean>() {
                    @Override
                    public CartAddUuBean reduce(CartAddUuBean t1, CartAddUuBean t2) throws Exception {
                        t2.setCartAddUuCt(t2.getCartAddUuCt() + t1.getCartAddUuCt());
                        return t2;
                    }
                }, new AllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<CartAddUuBean> values, Collector<CartAddUuBean> out) throws Exception {
                        CartAddUuBean result = values.iterator().next();
                        result.setStt(TimeUtil.parseDateStr(window.getStart(),true));
                        result.setEdt(TimeUtil.parseDateStr(window.getEnd(),true));
                        result.setTs(System.currentTimeMillis());
                        out.collect(result);
                    }
                });
    }

    private SingleOutputStreamOperator<CartAddUuBean> toCartAddUuBean(DataStreamSource<String> ds) {
        return ds.map(JSON::parseObject)
                .keyBy(j -> j.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, CartAddUuBean>() {

                    private ValueState<String> flagDate;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        flagDate = getRuntimeContext().getState(new ValueStateDescriptor<String>("flagDate", String.class));
                    }

                    @Override
                    public void processElement(JSONObject value, KeyedProcessFunction<String, JSONObject, CartAddUuBean>.Context ctx, Collector<CartAddUuBean> out) throws Exception {
                        long ts = value.getLong("ts") * 1000;
                        String currentDate = TimeUtil.parseDateStr(ts, false);
                        long cartAddUuCt = 0L;
                        if (!currentDate.equals(flagDate.value())){
                            flagDate.update(currentDate);
                            cartAddUuCt = 1L;
                        }
                        if (cartAddUuCt != 0) {
                            out.collect(
                                    CartAddUuBean.builder()
                                            .cartAddUuCt(cartAddUuCt)
                                            .ts(ts)
                                            .build()
                            );
                        }
                    }
                });
    }
}
